from sqlalchemy.orm import Session
from schema import Meteorology_schema
from model import Meteorology_model



def get_Meteorology(db: Session, ID: int):
    return db.query(Meteorology_model.Meteorology).filter(Meteorology_model.Meteorology.ID == ID).first()


def get_all_Meteorology(db: Session):
    return db.query(Meteorology_model.Meteorology).all()


def delete_Meteorology(db: Session, ID):
    to_delete = db.query(Meteorology_model.Meteorology).filter(Meteorology_model.Meteorology.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Meteorology(db: Session, Meteorology: Meteorology_schema.Meteorology):
    db_Meteorology = Meteorology_model.Meteorology(
        RetrievalTime=Meteorology.RetrievalTime,
        FarmID=Meteorology.FarmID,
        MaxTemperature=Meteorology.MaxTemperature,
        MinTemperature=Meteorology.MinTemperature,
        AvgVaporPressure=Meteorology.AvgVaporPressure,
        WindSpeed=Meteorology.WindSpeed,
        Precipitation=Meteorology.Precipitation,
        GlobalRadiation=Meteorology.GlobalRadiation,
        OtherIndicators=Meteorology.OtherIndicators,
    )
    db.add(db_Meteorology)
    db.commit()
    db.refresh(db_Meteorology)
    return db_Meteorology


def update_Meteorology(db: Session, ID, field_name, new_value):
    db_Meteorology = db.query(Meteorology_model.Meteorology).filter(Meteorology_model.Meteorology.ID == ID).first()
    setattr(db_Meteorology, field_name, new_value)
    db.commit()
    db.refresh(db_Meteorology)
    return db_Meteorology
